package com.example.munidingwei.ui.components

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp

/**
 * 后台服务器配置对话框
 * 允许用户配置和测试后台服务器连接
 */
@Composable
fun ServerConfigDialog(
    currentUrl: String,
    isConnected: Boolean,
    onDismiss: () -> Unit,
    onSave: (String) -> Unit,
    onConnect: (String) -> Unit,
    onDisconnect: () -> Unit
) {
    var serverUrl by remember { mutableStateOf(currentUrl) }
    var showPresets by remember { mutableStateOf(false) }
    
    // 预设服务器地址
    val presetServers = listOf(
        ServerPreset("默认服务器", "https://myedu.webn.cc/backend-php/api.php", "PHP HTTP API后台（推荐）"),
        ServerPreset("本地测试", "http://192.168.1.100:5000", "用于本地网络测试"),
        ServerPreset("Python后台", "http://your-server:5000", "Python + Flask后台"),
        ServerPreset("PHP WebSocket", "http://your-server:8080", "PHP WebSocket后台")
    )
    
    AlertDialog(
        onDismissRequest = onDismiss,
        icon = {
            Icon(
                imageVector = Icons.Default.Settings,
                contentDescription = null,
                tint = MaterialTheme.colorScheme.primary
            )
        },
        title = {
            Text(
                text = "后台服务器配置",
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.Bold
            )
        },
        text = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .verticalScroll(rememberScrollState()),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // 连接状态
                if (isConnected) {
                    Card(
                        modifier = Modifier.fillMaxWidth(),
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.primaryContainer
                        )
                    ) {
                        Row(
                            modifier = Modifier.padding(16.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                                imageVector = Icons.Default.CheckCircle,
                                contentDescription = null,
                                tint = MaterialTheme.colorScheme.primary,
                                modifier = Modifier.size(24.dp)
                            )
                            Spacer(modifier = Modifier.width(12.dp))
                            Column {
                                Text(
                                    text = "✅ 已连接",
                                    style = MaterialTheme.typography.titleMedium,
                                    fontWeight = FontWeight.Bold,
                                    color = MaterialTheme.colorScheme.onPrimaryContainer
                                )
                                Text(
                                    text = "后台服务器运行正常",
                                    style = MaterialTheme.typography.bodySmall,
                                    color = MaterialTheme.colorScheme.onPrimaryContainer
                                )
                            }
                        }
                    }
                }
                
                // 服务器地址输入
                OutlinedTextField(
                    value = serverUrl,
                    onValueChange = { serverUrl = it },
                    label = { Text("服务器地址") },
                    placeholder = { Text("http://192.168.1.100:5000") },
                    leadingIcon = {
                        Icon(
                            imageVector = Icons.Default.LocationOn,
                            contentDescription = null
                        )
                    },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    supportingText = {
                        Text(
                            text = "输入后台服务器的完整URL地址",
                            style = MaterialTheme.typography.bodySmall
                        )
                    }
                )
                
                // 预设服务器按钮
                OutlinedButton(
                    onClick = { showPresets = !showPresets },
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Icon(
                        imageVector = if (showPresets) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                        contentDescription = null
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("预设服务器地址")
                }
                
                // 预设服务器列表
                if (showPresets) {
                    Card(
                        modifier = Modifier.fillMaxWidth(),
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.surfaceVariant
                        )
                    ) {
                        Column(modifier = Modifier.padding(8.dp)) {
                            presetServers.forEach { preset ->
                                ServerPresetItem(
                                    preset = preset,
                                    onClick = { 
                                        serverUrl = preset.url
                                        showPresets = false
                                    }
                                )
                            }
                        }
                    }
                }
                
                Divider()
                
                // 说明文本
                Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    Text(
                        text = "💡 配置说明：",
                        style = MaterialTheme.typography.titleSmall,
                        fontWeight = FontWeight.Bold
                    )
                    
                    InfoItem(
                        icon = Icons.Default.Info,
                        text = "确保设备和服务器在同一网络"
                    )
                    
                    InfoItem(
                        icon = Icons.Default.Info,
                        text = "使用实际IP地址，不要用localhost"
                    )
                    
                    InfoItem(
                        icon = Icons.Default.Info,
                        text = "检查服务器防火墙是否开放端口"
                    )
                    
                    InfoItem(
                        icon = Icons.Default.CheckCircle,
                        text = "支持Python、PHP WebSocket和PHP HTTP后台"
                    )
                }
                
                Divider()
                
                // 示例地址
                Text(
                    text = "示例地址：",
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.Bold
                )
                
                Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
                    ExampleUrl("http://192.168.1.100:5000")
                    ExampleUrl("http://your-domain.com:8080")
                    ExampleUrl("https://api.yourdomain.com")
                }
            }
        },
        confirmButton = {
            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                if (isConnected) {
                    Button(
                        onClick = {
                            onDisconnect()
                            onDismiss()
                        },
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.error
                        )
                    ) {
                        Icon(
                            imageVector = Icons.Default.Close,
                            contentDescription = null,
                            modifier = Modifier.size(18.dp)
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text("断开")
                    }
                }
                
                Button(
                    onClick = {
                        onSave(serverUrl)
                        onConnect(serverUrl)
                        onDismiss()
                    },
                    enabled = serverUrl.isNotBlank()
                ) {
                    Icon(
                        imageVector = Icons.Default.Check,
                        contentDescription = null,
                        modifier = Modifier.size(18.dp)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(if (isConnected) "保存并重连" else "保存并连接")
                }
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}

@Composable
private fun ServerPresetItem(
    preset: ServerPreset,
    onClick: () -> Unit
) {
    OutlinedCard(
        onClick = onClick,
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp)
    ) {
        Column(modifier = Modifier.padding(12.dp)) {
            Text(
                text = preset.name,
                style = MaterialTheme.typography.titleSmall,
                fontWeight = FontWeight.Bold
            )
            Text(
                text = preset.url,
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.primary,
                fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace
            )
            Text(
                text = preset.description,
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

@Composable
private fun InfoItem(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    text: String
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.Top
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            modifier = Modifier.size(16.dp),
            tint = MaterialTheme.colorScheme.primary
        )
        Spacer(modifier = Modifier.width(8.dp))
        Text(
            text = text,
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

@Composable
private fun ExampleUrl(url: String) {
    Surface(
        color = MaterialTheme.colorScheme.surfaceVariant,
        shape = MaterialTheme.shapes.small
    ) {
        Text(
            text = url,
            modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
            style = MaterialTheme.typography.bodySmall,
            fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

data class ServerPreset(
    val name: String,
    val url: String,
    val description: String
)

